package com.ai.exam.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Date:  2018/5/31
 * Time:  14:35
 * Email: siy@hmgsoft.com
 * Created by siy
 */
@RestController
public class TestController {
    private Logger logger = LoggerFactory.getLogger(TestController.class);
    private String serverUrl = "http://wx.10086.cn/operation/api/out/getFansInfoByOauth2";
    @Value("${my-moblie.appid}")
    private String appid;
    @Value("${my-moblie.accountID}")
    private String  accountID;

    @GetMapping("getCode")
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        logger.info("进入getCode");
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        Thread.sleep(10000);

        StringBuffer backUrl = new StringBuffer(
                "http://localhost:8080/#/home?status=0000"+
                        "&message=12333333"+
                        "&openId=oJAS9uB-JVKq9uqjHkwqOcT4gD_E"+
                        "&telNum=1900000"
        );
        response.sendRedirect(backUrl.toString());//这里请不要使用get请求单纯的将页面跳转到该url即可
    }


    @GetMapping("test1")
    public String test1() throws JsonProcessingException {
        logger.info("test1======="+accountID);
        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        ObjectMapper mapper = new ObjectMapper();
//        Map<String, String> params= Maps.newHashMap();
//        params.put("accountId", accountID);
//        params.put("url", "www.baidu.com");
//        String value = mapper.writeValueAsString(params);
//        HttpEntity<String> requestEntity = new HttpEntity<String>(value, headers);
//        //  执行HTTP请求
//        ResponseEntity<String> response = template.postForEntity(serverUrl, requestEntity , String.class );
//        logger.info("请求结果：{}",response.getBody());

        //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        //  封装参数，千万不要替换为Map与HashMap，否则参数无法传递
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        params.add("accountId",accountID);
        params.add("code","011JtM7e2CJvpD0BAM8e2LQB7e2JtM7z");
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  执行HTTP请求
        ResponseEntity<String> response = template.exchange(serverUrl, HttpMethod.POST, requestEntity, String.class);
        //  输出结果
        String body = response.getBody();
        logger.info("请求结果：{}",body);
        return null;
    }

    @GetMapping("test2")
    public String test2(){
        RestTemplate template = new RestTemplate();
        logger.info("test2=======");
        String url = "http://wx.10086.cn/operation/api/out/getFansInfoByOauth2?accountId={accountId}&code={code}";

        Map<String, Object> uriVariables = new HashMap<String, Object>();
        uriVariables.put("accountId", accountID);
        uriVariables.put("code", "011JtM7e2CJvpD0BAM8e2LQB7e2JtM7z");

        String result = template.getForObject(url, String.class, uriVariables);
        System.out.println(result);
        return null;
    }

    @GetMapping("test3")
    public String test3(){
        Map map = new HashMap();
        map.put("accountId",accountID);
        map.put("code","00101ENB1tJ5Fe0XlPMB16OpNB101ENE");
        //map.put("openId","oJAS9uBK5_5LoRFqKkwEk4QE7XPw");
        String rs = restTemplate("http://wx.10086.cn/operation/api/out/v2/getFansInfoByOauth2",map,String.class,HttpMethod.GET);
        return rs;
    }

    public <T> T restTemplate(String url, Map<String,T> params, Class<T> var, HttpMethod method) {
        RestTemplate restTemplate = new RestTemplate();
        FormHttpMessageConverter fc = new FormHttpMessageConverter();
        StringHttpMessageConverter s = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>();
        partConverters.add(s);
        partConverters.add(new ResourceHttpMessageConverter());
        fc.setPartConverters(partConverters);
        restTemplate.getMessageConverters().addAll(Arrays.asList(fc, new MappingJackson2HttpMessageConverter()));
        MultiValueMap<String, T> map = new LinkedMultiValueMap<>();
        map.setAll(params);
        switch (method) {
            case POST:
                return restTemplate.postForObject(url, map, var);
            case GET:
                String getParams = "?" + map.keySet().stream().map(k -> String.format("%s={%s}", k, k)).collect(Collectors.joining("&"));
                return restTemplate.getForObject(url + getParams, var, params);
            default:
                return restTemplate.postForObject(url, map, var);
        }
    }
}
